package com.woniuxy.juc.reentrant;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: ReentrantLock 实现循环打印
 * <P> Date: 2022/4/8:12:26
 * <P> Description:
 */
@Slf4j(topic = "c.ReentrantLockLoopPrint")
public class ReentrantLockLoopPrint {
    public static void main(String[] args) throws InterruptedException {
        AwaitSignal awaitSignal = new AwaitSignal(5);
        Condition a = awaitSignal.newCondition();
        Condition b = awaitSignal.newCondition();
        Condition c = awaitSignal.newCondition();
        new Thread(()->{
            awaitSignal.print("a",a,b);
        },"t1").start();


        new Thread(()->{
            awaitSignal.print("b",b,c);
        },"t2").start();


        new Thread(()->{
            awaitSignal.print("c",c,a);
        },"t3").start();
        Thread.sleep(1000);

        awaitSignal.lock();

        try {
            log.debug("主线程叫醒");
            a.signal();
        }finally {
            awaitSignal.unlock();
        }
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class AwaitSignal extends ReentrantLock {
    private int loopNumber;

    /**
        * TODO:参数1 打印内容 参数2 进入指定的休息室 参数3 叫醒下一个休息室
    **/
    public void print(String str,
                      Condition condition,
                      Condition next){
        for (int i = 0; i < loopNumber; i++) {
            lock();
            try {
                condition.await();
                System.out.println(str);
                next.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                unlock();
            }
        }
    }
}
